package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.SetmealMapper;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import com.sky.service.SetmealDishService;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryService categoryService;
    @Override
    public List<DishItemVO> getDishItemById(Long id) {
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishes = setmealDishService.list(lambdaQueryWrapper);
        List<DishItemVO> dishItemVOS = setmealDishes.stream().map(item -> {
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dish::getId, item.getDishId());
            Dish dish = dishService.getOne(queryWrapper);
            DishItemVO dishItemVO = DishItemVO.builder()
                    .name(item.getName())
                    .copies(item.getCopies())
                    .image(dish.getImage())
                    .description(dish.getDescription())
                    .build();
            return dishItemVO;
        }).collect(Collectors.toList());
        return dishItemVOS;
    }

    @Override
    @Transactional
    public void saveWithDish(SetmealDTO setmealDto) {
        //保存套餐的基本信息，操作setmeal，执行insert操作
        Long currentId = BaseContext.getCurrentId();
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto,setmeal);
        setmeal.setStatus(StatusConstant.DISABLE);
        setmeal.setCreateUser(currentId);
        setmeal.setUpdateUser(currentId);
        setmeal.setCreateTime(LocalDateTime.now());
        setmeal.setUpdateTime(LocalDateTime.now());
        super.save(setmeal);
        //保存套餐和菜品的关联信息，操作setmeal_dish,执行insert操作
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().map(item->{
            item.setSetmealId(setmeal.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);

    }

    @Override
    public Page<SetmealVO> pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {

        int page = setmealPageQueryDTO.getPage();
        int pageSize = setmealPageQueryDTO.getPageSize();
        Integer categoryId = setmealPageQueryDTO.getCategoryId();
        Integer status = setmealPageQueryDTO.getStatus();
        String name = setmealPageQueryDTO.getName();

        Page<Setmeal> pageinfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(name!=null,Setmeal::getName,name)
                .eq(categoryId!=null,Setmeal::getCategoryId,categoryId)
                .eq(status!=null,Setmeal::getStatus,status)
                .orderByDesc(Setmeal::getUpdateTime);
        super.page(pageinfo, lambdaQueryWrapper);

        Page<SetmealVO> voPage = new Page<>();
        BeanUtils.copyProperties(pageinfo,voPage,"records");
        List<Setmeal> records = pageinfo.getRecords();
        List<SetmealVO> setmealVOS = records.stream().map(item -> {
            SetmealVO setmealVO = new SetmealVO();
            BeanUtils.copyProperties(item, setmealVO);
            Long itemCategoryId = item.getCategoryId();
            Category category = categoryService.getById(itemCategoryId);
            if (category != null) {
                String categoryName = category.getName();
                setmealVO.setCategoryName(categoryName);
            }
            return setmealVO;
        }).collect(Collectors.toList());
        voPage.setRecords(setmealVOS);
        return voPage;
    }

    @Override
    public SetmealVO getSetmealWithDish(Long id) {
        Setmeal setmeal = super.getById(id);
        SetmealVO setmealVO = new SetmealVO();
        Long categoryId = setmeal.getCategoryId();
        Category category = categoryService.getById(categoryId);
        String categoryName = category.getName();
        BeanUtils.copyProperties(setmeal,setmealVO);
        setmealVO.setCategoryName(categoryName);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,id);
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
        setmealVO.setSetmealDishes(setmealDishes);
        return setmealVO;
    }

    @Override
    public void updateWithDish(SetmealDTO setmealDTO) {
        //更新setmeal表基本信息
        Long currentId = BaseContext.getCurrentId();
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        setmeal.setStatus(StatusConstant.DISABLE);
        setmeal.setUpdateUser(currentId);
        setmeal.setUpdateTime(LocalDateTime.now());
        super.updateById(setmeal);
        //清理当前套餐对应菜品数据---setmeal_dish表的delete操作
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealDTO.getId());
        setmealDishService.remove(queryWrapper);
        //添加当前提交的菜品数据---setmeal_dish表的insert操作
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map(item -> {
            item.setSetmealId(setmealDTO.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    public void updateStatus(int status,Long id) {
        Setmeal setmeal = super.getById(id);
        setmeal.setStatus(status);
        setmeal.setUpdateTime(LocalDateTime.now());
        setmeal.setUpdateUser(BaseContext.getCurrentId());
        super.updateById(setmeal);
    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //查询套餐状态，确定是否可以删除
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,ids);
        queryWrapper.eq(Setmeal::getStatus,1);
        int count = super.count(queryWrapper);
        //如果不能删除，抛出业务异常
        if(count>0){
            throw new DeletionNotAllowedException("套餐正在售卖,不能删除");
        }
        //如果可以删除，先删除套餐表的数据--setmeal
        super.removeByIds(ids);
        //再删除关系表的数据--setmea_dish
        //delete from setmeal_dish where setmeal_id in (1,2,3)
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper);

    }
}
